#!/usr/bin/env node

var opentype = require('opentype.js');
var GCanvas = require('../lib/svg2gcode/gcanvas'); // gcode 生成画布
var GCodeDriver = require('../lib/svg2gcode/drivers/gcode');
var fs = require('fs');

var font = 'lib/svg2gcode/fonts/SIMHEI.TTF';
// var font = '../lib/svg2gcode/fonts/OpenSans-Bold-webfont.woff';
var fontsize = 20; // 字体大小

var text = '创鑫，激光！';
// var text = 'HELLO WORLD！';


opentype.load(font, function (err, font) {
    if (err) {
        console.error(err);
        return;
    }

    var width = 0;
    font.forEachGlyph(text + ' ', 0, 0, fontsize, null, function (glyph, x, y) {
        width = x;
    })

    var x = 0;
    var y = 0;

    var path = font.getPath(text, 0, 0, fontsize, null);
    path.lineWidth = 0.005;
    path.stroke = 'black';
    path.fill = 'black';

    // console.log(path.toPathData());

    var gcode = [];

    var gcodeDriver = new GCodeDriver({
        write: function (str) {
            gcode.push(str); // 将接收到的字符串写入 gcode 变量
        }
    });
    var gctx = new GCanvas(gcodeDriver);
    gctx.setSpeedMax(200);
    gctx.setFeed(30000);
    gctx.toolDiameter = 0.01;

    gctx.transform(1, 0, 0, -1, 0, 0); // 绕 x 轴翻转
    gctx.setFillDir(6);
    gctx.motion.setPreviewMode(false);
    gctx.motion.initDriver();

    path.draw(gctx);
    // gctx.fill('evenodd');
    // console.log(gcode.join('\n'));
    // 输出生成的 Gcode
    // console.log(gcode);
    gctx.motion.finishProgram();
    build({ code: gcode, outputFilename: './opentype_use.gcode', filename: 'opentype_use' });

    console.log("All Done!!!");
})


// 将 gcode 数组保存到文件
function build({ code, outputFilename, filename }) {
    const file = outputFilename ? outputFilename : `./${filename}.gcode`;
    fs.writeFileSync(file, code.join("\n"));
    return Promise.resolve();
};

